package com.gxb.codebook;

import android.annotation.SuppressLint;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Rect;
import android.os.Bundle;
import android.view.View;
import android.view.ViewTreeObserver;
import android.view.WindowManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.activity.EdgeToEdge;
import androidx.appcompat.app.AppCompatActivity;
import androidx.localbroadcastmanager.content.LocalBroadcastManager;

import com.gxb.codebook.bean.NotepadBean;
import com.gxb.codebook.database.SQLiteHelper;
import com.gxb.codebook.utils.DBUtils;

import java.text.SimpleDateFormat;
import java.util.Date;

public class RecordActivity extends AppCompatActivity implements View.OnClickListener {
    private ImageView note_back;
    private TextView note_time;
    private EditText content;
    private ImageView delete;
    private ImageView note_save;
    private SQLiteHelper mSQLiteHelper;
    private TextView noteName;
    private String id;
    private ScrollView scrollView;
    private View scrollContent;
    private BroadcastReceiver themeChangeReceiver;
    private LocalBroadcastManager localBroadcastManager;

    @SuppressLint("UnspecifiedRegisterReceiverFlag")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EdgeToEdge.enable(this);
        setContentView(R.layout.activity_record);

        // 初始化LocalBroadcastManager
        localBroadcastManager = LocalBroadcastManager.getInstance(this);

        // 初始化广播接收器
        themeChangeReceiver = new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {
                if ("THEME_CHANGED".equals(intent.getAction())) {
                    recreate();
                }
            }
        };

        // 注册广播接收器
        IntentFilter filter = new IntentFilter("THEME_CHANGED");
        localBroadcastManager.registerReceiver(themeChangeReceiver, filter);

        scrollView = findViewById(R.id.scrollView);
        scrollContent = findViewById(R.id.scroll_content);
        getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE);

        note_back = findViewById(R.id.note_back);
        note_time = findViewById(R.id.tv_time);
        content = findViewById(R.id.note_content);
        delete = findViewById(R.id.delete);
        note_save = findViewById(R.id.note_save);
        noteName = findViewById(R.id.note_name);

        note_back.setOnClickListener(this);
        delete.setOnClickListener(this);
        note_save.setOnClickListener(this);

        initData();

        // 添加全局布局监听器以检测软键盘的显示
        scrollView.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
            @Override
            public void onGlobalLayout() {
                Rect r = new Rect();
                scrollView.getWindowVisibleDisplayFrame(r);
                int screenHeight = scrollView.getRootView().getHeight();
                int keypadHeight = screenHeight - r.bottom;
                if (keypadHeight > screenHeight * 0.15) { // 0.15 的比例足以确定键盘高度
                    scrollContent.setPadding(0, 0, 0, keypadHeight);
                } else {
                    scrollContent.setPadding(0, 0, 0, 0);
                }
            }
        });
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (localBroadcastManager != null && themeChangeReceiver != null) {
            localBroadcastManager.unregisterReceiver(themeChangeReceiver);
        }
    }

    protected void initData() {
        mSQLiteHelper = new SQLiteHelper(this);
        noteName.setText("添加");
        Intent intent = getIntent();
        if (intent != null) {
            id = intent.getStringExtra("id");
            if (id != null) {
                noteName.setText("修改");
                content.setText(intent.getStringExtra("content"));
                Date date = new Date();
                SimpleDateFormat formatter = new SimpleDateFormat("yyyy年MM月dd日 HH:mm");
                String time = formatter.format(date);
                note_time.setText(time);

                // 发送笔记加载完成广播
                Intent loadIntent = new Intent("NOTE_LOADED");
                loadIntent.putExtra("id", id);
                localBroadcastManager.sendBroadcast(loadIntent);
            }
        }
    }

    @Override
    public void onClick(View v) {
        if (v.getId() == R.id.note_back) {
            // 发送返回按钮点击广播
            Intent backIntent = new Intent("NOTE_BACK_CLICKED");
            localBroadcastManager.sendBroadcast(backIntent);

            // finish();
        } else if (v.getId() == R.id.delete) {
            content.setText("");

            // 发送清空内容广播
            Intent clearIntent = new Intent("NOTE_CONTENT_CLEARED");
            localBroadcastManager.sendBroadcast(clearIntent);
        } else if (v.getId() == R.id.note_save) {
            String noteContent = content.getText().toString().trim();
            if (id != null) { // 修改操作
                if (noteContent.length() > 0) {
                    if (mSQLiteHelper.updateData(id, noteContent, DBUtils.getTime())) {
                        showToast("修改成功");
                        setResult(2);

                        // 发送笔记修改成功广播
                        Intent updateIntent = new Intent("NOTE_UPDATED");
                        updateIntent.putExtra("id", id);
                        updateIntent.putExtra("content", noteContent);
                        localBroadcastManager.sendBroadcast(updateIntent);

                        // finish();
                    } else {
                        showToast("修改失败");

                        // 发送笔记修改失败广播
                        Intent failIntent = new Intent("NOTE_UPDATE_FAILED");
                        failIntent.putExtra("id", id);
                        localBroadcastManager.sendBroadcast(failIntent);
                    }
                } else {
                    showToast("修改内容不能为空!");

                    // 发送笔记内容为空广播
                    Intent emptyIntent = new Intent("NOTE_CONTENT_EMPTY");
                    emptyIntent.putExtra("operation", "update");
                    localBroadcastManager.sendBroadcast(emptyIntent);
                }
            } else {
                // 向数据库中添加数据
                if (noteContent.length() > 0) {
                    if (mSQLiteHelper.insertData(noteContent, DBUtils.getTime())) {
                        showToast("保存成功");
                        setResult(2);

                        // 发送笔记保存成功广播
                        Intent saveIntent = new Intent("NOTE_SAVED");
                        saveIntent.putExtra("content", noteContent);
                        localBroadcastManager.sendBroadcast(saveIntent);

                        // finish();
                    } else {
                        showToast("保存失败");

                        // 发送笔记保存失败广播
                        Intent failIntent = new Intent("NOTE_SAVE_FAILED");
                        localBroadcastManager.sendBroadcast(failIntent);
                    }
                } else {
                    showToast("内容不能为空!");

                    // 发送笔记内容为空广播
                    Intent emptyIntent = new Intent("NOTE_CONTENT_EMPTY");
                    emptyIntent.putExtra("operation", "save");
                    localBroadcastManager.sendBroadcast(emptyIntent);
                }
            }
        }
    }

    public void showToast(String message) {
        Toast.makeText(RecordActivity.this, message, Toast.LENGTH_SHORT).show();
    }
}
